from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView

from goods.models import GoodsCategory, SKU
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.serializers import GoodsSerializers, SKUIndexSerializer, UserGoodsHistorySerializer
from goods.utils import GoodsPage
from django_redis import get_redis_connection


class GoodCategorieView(APIView):

    def get(self, request, pk):
        # 获取三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)
        #  获取二级分类对象和获取一级分类对象
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })


class GoodsView(ListAPIView):
    """
        商品列表页数据获取
    """
    # queryset = SKU.objects.filter(category_id=)
    serializer_class = GoodsSerializers
    #  设置分页
    pagination_class = GoodsPage
    # 排序
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    def get_queryset(self):
        pk = self.kwargs['pk']

        return SKU.objects.filter(category_id=pk)


class SKUIndexView(HaystackViewSet):
    pagination_class = GoodsPage

    # 指定模型类对象
    index_models = [SKU]

    serializer_class = SKUIndexSerializer


class UserGoodsHistoryView(CreateAPIView,ListAPIView):
    '''
    保存和获取用户浏览打商品信息
    '''

    # serializer_class = UserGoodsHistorySerializer

    # queryset = SKU.objects.filter(id__in=)
    def get_serializer_class(self):
        # 根据不同打请求方式,返回不同打序列化器
        if self.request.method == "POST":
            return UserGoodsHistorySerializer
        else:
            return GoodsSerializers

    def get_queryset(self):
        # 链接redis缓存
        conn = get_redis_connection("history")
        user = self.request.user
        # 获取列表数据
        sku_id = conn.lrange('history_%s' % user.id,0,5)

        return SKU.objects.filter(id__in=sku_id)
